package com.df.ez_game.server;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.df.ez_game.net.Connector;
import com.df.ez_game.net.TcpConnector;
import com.df.ez_game.server.broker.BrokerMsg;
import io.netty.channel.ChannelHandlerContext;

public class BrokerInfo {
    private String ip;
    private Integer port;
    private int status;//0未连接 1连接成功
    // 最后心跳时间戳
    private long lastHeartbeatTime = 0;
    // 服务类型（默认Broker）
    private NodeType serviceType = NodeType.MsgBus;
    // 节点权重（负载均衡用）
    private int weight = 100;
    Connector connector;

    public BrokerInfo(String ip, int port, NodeType serviceType) {
        this.ip = ip;
        this.port = port;
        this.serviceType = serviceType;
    }

    public BrokerInfo(String ip, int port) {
        this(ip, port, NodeType.MsgBus);
    }

    void connect(){
        if(status==1){
            return;
        }
        if(connector==null){
            connector = new TcpConnector(ip,port,-1,2000L);
            // 添加连接状态监听器
            connector.setConnectListener(connected -> {
                if (connected) {
                    status = 1; // 连接成功更新状态
                }
            });
            connector.connect();
        }
        // 连接成功后更新心跳时间
        updateHeartbeat();
    }

    /**
     * 更新心跳时间
     */
    public void updateHeartbeat() {
        lastHeartbeatTime = System.currentTimeMillis();
    }

    /**
     * 检查节点是否存活
     * @param timeout 超时时间（毫秒）
     * @return 是否存活
     */
    public boolean checkAlive(long timeout) {
        if (lastHeartbeatTime == 0) {
            return false; // 从未收到过心跳
        }
        return (System.currentTimeMillis() - lastHeartbeatTime) <= timeout;
    }

    /**
     * 像broker发送消息
     *
     * @param ctx 客户端连接的上下文
     * @param brokerMsg
     */
    public void sendMsg(ChannelHandlerContext ctx, BrokerMsg brokerMsg){
        if(status==0){
            return;
        }
        Codec<BrokerMsg> codec = ProtobufProxy.create(BrokerMsg.class);
        try {
            byte[] encode = codec.encode(brokerMsg);
            connector.sendMsg(encode);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
